package com.service.Impl;

import com.pojo.dto.Message;
import com.pojo.vo.PictureVo;
import com.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("/PictureService")
public class PictureServiceImpl implements PictureService {

    @Value("${prop.upload-picture}")//图片存储路径
    private String UPLOAD_FOLDER;

    @Override
    public Message<PictureVo> add(PictureVo pictureVo) {
        MultipartFile file = pictureVo.getFile();
        if (Objects.isNull(file) || file.isEmpty()) {
            return Message.errorMessage("1001", "文件为空，请重新上传");
        }
        String videoName = file.getOriginalFilename();//获取文件名称
        String toLowerCase = videoName.substring(videoName.lastIndexOf(".") + 1, videoName.length()).toLowerCase();//获取上传文件的文件类型
        String img[] = {"jpg", "png"};
        //判断文件类型,图片为jpg和png格式的话才可以
        for (int i = 0; i < img.length; i++) {
            if ((img[i].equals(toLowerCase))) {
                try {
                    byte[] bytes = file.getBytes();
                    Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
                    //如果没有files文件夹，则创建
                    if (!Files.isWritable(path)) {
                        Files.createDirectories(Paths.get(UPLOAD_FOLDER));
                    }
                    //文件写入指定路径
                    Files.write(path, bytes);
                    String pathVideo = String.valueOf(path);//video的原始存储
                    String videoTruth = pathVideo.substring(pathVideo.lastIndexOf("\\") + 1);//获取video


                    //String s = pathVideo.replace('\\','/');
                    PictureVo picture = new PictureVo();
                    picture.setPicturePath("http://wgy.vaiwan.com/files/pics/" + videoTruth);
                    return Message.successMessage(1L, picture);


                } catch (IOException e) {
                    e.printStackTrace();
                    return Message.errorMessage("1001", "后端异常...");

                }

            }
        }
        return Message.errorMessage("1001", "上传文件格式不符合，请重新上传...");
    }

    @Override
    public Message<List<PictureVo>> addList(List<PictureVo> pictures) {
        List<PictureVo> list = new ArrayList<>();
        for (int i = 0; i < pictures.size(); i++) {
            PictureVo data = add(pictures.get(i)).getData();
            list.add(data);
        }
        return Message.successMessage(1L, list);
    }
}
